package net.chenyan.server.controller.admapi;/**
 * @author chenyan
 * @createTime 2022/5/8 21:19
 * @description description
 */

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import net.chenyan.commons.core.R;
import net.chenyan.server.po.*;
import net.chenyan.server.service.SingerService;
import net.chenyan.server.service.UserService;
import net.chenyan.server.service.UserSingerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.web.bind.annotation.*;

/**
 *@description: TODO
 *@author: chenyan
 *@create: 2022/5/8 21:19
 */
@Slf4j
@Api(tags = {"用户歌手接口"})
@RestController
@RequestMapping(value = "/admapi/userSinger")
public class UserSingerController {
    @Autowired
    private UserService userService;
    @Autowired
    private SingerService singerService;
    @Autowired
    private UserSingerService userSingerService;

    @ApiOperation(value = "用户关注/取消关注歌手")
    @PostMapping(value = "/update")
    public R updateById(@RequestBody int userId, int singerId) {
        User user=userService.getById(userId);
        Singer singer=singerService.getById(singerId);
        if(user==null || singer==null){
            return R.error("用户id或者歌手id不存在！");
        }
        QueryWrapper<UserSinger> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("user_id",userId);
        queryWrapper.eq("singer_id",singerId);
        UserSinger userSinger=userSingerService.getOne(queryWrapper);
        int fansNum=singer.getFansNum();
        if(userSinger==null){
            UserSinger userSinger1=new UserSinger();
            userSinger1.setUserId(userId);
            userSinger1.setSingerId(singerId);
            boolean temp =userSingerService.save(userSinger1);
            singer.setFansNum(fansNum+1);
            singerService.updateById(singer);
            return temp ? R.ok("关注成功！") : R.error("关注失败！");
        }
        userSingerService.removeById(userSinger.getId());
        singer.setFansNum(fansNum-1);
        singerService.updateById(singer);
        return R.ok("取消关注成功！");
        }

    @ApiOperation(value = "获取用户关注的歌手")
    @PostMapping(value = "/getSingerByUserId")
    public R getSingerByUserId(int userId, @RequestParam(defaultValue = "0")int page, @RequestParam(defaultValue = "5")int size) {
        return R.data(singerService.findAllSingerByUserId(PageRequest.of(page,size),userId));
    }


}
